﻿// ZipCodeValidator
(function ($) {
    $.validator.addMethod('zipvalidator', function (value, element, params) {
        var dependant = params.dependantproperty;

        var patterns = jQuery.evalJSON(params.patterns);

        var currentVal = value + '';

        var $dependant = $('#' + dependant);

        var dependantVal = ($dependant.attr('type') && $dependant.attr('type').toUpperCase() == "CHECKBOX") ?
                            ($dependant.attr("checked") ? "true" : "false") :
                            $dependant.val();

        var pattern = patterns[dependantVal];

        if (!pattern) return true;

        var regex = new RegExp(pattern);

        if (!currentVal.match(regex)) {
            return false;
        }

        return true;
    });

    $.validator.unobtrusive.adapters.add('zipvalidator', ['dependantproperty', 'patterns'], function (options) {
        options.rules['zipvalidator'] = {
            dependantproperty: options.params.dependantproperty,
            patterns: options.params.patterns
        };
        options.messages['zipvalidator'] = options.message;
    });
}(jQuery));